<script setup>
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '产品A1',
    price: 98.5,
    category: '电子产品',
    inventory: 120,
    createdAt: '2023-05-10'
  },
  {
    id: 2,
    name: '产品B',
    price: 199,
    category: '家居用品',
    inventory: 85,
    createdAt: '2023-05-12'
  },
  {
    id: 3,
    name: '产品C',
    price: 49.9,
    category: '食品',
    inventory: 300,
    createdAt: '2023-05-15'
  },
  {
    id: 4,
    name: '产品D',
    price: 399,
    category: '电子产品',
    inventory: 50,
    createdAt: '2023-05-18'
  },
  {
    id: 5,
    name: '产品E',
    price: 799,
    category: '电子产品',
    inventory: 30,
    createdAt: '2023-05-20'
  }
])

// 表格加载状态
const loading = ref(false)

// 搜索条件
const searchForm = ref({
  name: '',
  category: ''
})

// 分类选项
const categoryOptions = [
  { label: '全部', value: '' },
  { label: '电子产品', value: '电子产品' },
  { label: '家居用品', value: '家居用品' },
  { label: '食品', value: '食品' }
]

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = computed(() => isEdit.value ? '编辑产品' : '新增产品')

// 分页设置
const currentPage = ref(1)
const pageSize = ref(20)

// 表单规则
const rules = {
  name: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur' }
  ],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  inventory: [
    { required: true, message: '请输入库存', trigger: 'blur' },
    { type: 'number', message: '库存必须为数字', trigger: 'blur' }
  ]
}

// 表单数据
const formData = ref({
  id: '',
  name: '',
  price: 0,
  category: '',
  inventory: 0,
  createdAt: ''
})

// 搜索方法
const handleSearch = () => {
  loading.value = true
  // 模拟搜索
  setTimeout(() => {
    const filteredData = tableData.value.filter(item => {
      const nameMatch = !searchForm.value.name || item.name.includes(searchForm.value.name)
      const categoryMatch = !searchForm.value.category || item.category === searchForm.value.category
      return nameMatch && categoryMatch
    })
    tableData.value = filteredData
    loading.value = false
  }, 500)
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    category: ''
  }
  handleSearch()
}

// 打开新增对话框
const handleAdd = () => {
  isEdit.value = false
  formData.value = {
    id: '',
    name: '',
    price: 0,
    category: '',
    inventory: 0,
    createdAt: new Date().toISOString().split('T')[0]
  }
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  isEdit.value = true
  formData.value = { ...row }
  dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
  ElMessageBox.alert(
    `<div>
      <p><strong>产品名称：</strong>${row.name}</p>
      <p><strong>价格：</strong>¥${row.price}</p>
      <p><strong>分类：</strong>${row.category}</p>
      <p><strong>库存：</strong>${row.inventory}</p>
      <p><strong>创建时间：</strong>${row.createdAt}</p>
    </div>`,
    '产品详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定'
    }
  )
}

// 删除数据
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该产品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

// 提交表单
const formRef = ref(null)
const handleSubmit = () => {
  if (!formRef.value) return

  formRef.value.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑模式
        const index = tableData.value.findIndex(item => item.id === formData.value.id)
        if (index > -1) {
          tableData.value[index] = { ...formData.value }
          ElMessage.success('修改成功')
        }
      } else {
        // 新增模式
        const newId = Math.max(...tableData.value.map(item => item.id)) + 1
        tableData.value.push({
          ...formData.value,
          id: newId
        })
        ElMessage.success('添加成功')
      }
      dialogVisible.value = false
    }
  })
}

// 导出数据
const handleExport = () => {
  ElMessage.success('导出功能待实现')
}
</script>

<template>
  <div class="table-container">
    <h2 class="table-title">产品列表</h2>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="产品名称">
          <el-input v-model="searchForm.name" placeholder="请输入产品名称" clearable />
        </el-form-item>
        <el-form-item label="产品分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
            <el-option
              v-for="item in categoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 功能按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新增产品
      </el-button>
      <el-button type="success" @click="handleExport">
        <el-icon><Download /></el-icon> 导出数据
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="产品名称" width="150" />
      <el-table-column prop="price" label="价格" width="100">
        <template #default="{ row }">
          {{ '¥' + row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="category" label="分类" width="120" />
      <el-table-column prop="inventory" label="库存" width="100">
        <template #default="{ row }">
          <el-tag :type="row.inventory > 50 ? 'success' : 'danger'">
            {{ row.inventory }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" width="150" />
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="success" @click="handleView(row)">查看</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :total="100"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="formData.price"
            :precision="2"
            :step="0.1"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="formData.category" placeholder="请选择分类" style="width: 100%">
            <el-option
              v-for="item in categoryOptions.filter(item => item.value)"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="库存" prop="inventory">
          <el-input-number
            v-model="formData.inventory"
            :min="0"
            :precision="0"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.table-container {
  padding: 15px;
  background-color: #fff;
  height: 100%;
  overflow: auto;
  display: flex;
  flex-direction: column;
}

.table-title {
  font-size: 18px;
  margin-bottom: 15px;
  font-weight: 500;
  color: #303133;
}

.search-form {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.action-buttons {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.el-table {
  flex: 1;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-input-number .el-input__wrapper) {
  padding-left: 11px;
  padding-right: 11px;
}
</style>
